from backend.api.connection import POOL
# from connection import POOL   # 单独运行用这个


# 用户注册
# 返回
# {'uid': 10086, 'ok': 1,'msg':''}

def userSignup(username, pwd):
    # 字符串一定要在外面套repr(), 巨坑！！！
    username = repr(username)
    pwd = repr(pwd)

    conn = POOL.connection()
    cur = conn.cursor()
    response = {'uid': 0, 'ok': 0, 'msg': ''}

    sql = ''
    # 查询用户名是否存在
    sql = 'SELECT count(*) FROM userinfo WHERE username = %s' % (username)
    cur.execute(sql)
    data = cur.fetchone()
    if data[0] != 0:
        response['msg'] = "用户名已存在"
        return response

# 新增用户
    sql = "INSERT INTO userinfo (username, password, type) VALUES(%s, %s, 0)" % (
        username, pwd)
    cur.execute(sql)
    uid = int(cur.lastrowid)
    print(uid)
    conn.commit()
    cur.close()
    response['uid'] = uid
    response['ok'] = 1

    print(response)
    return response


# 用户登录
# 返回
# {'uid': 10000, 'ok': 1, 'msg': ''}
# {'uid': 0, 'ok': 0, 'msg': '用户不存在'}
# {'uid': 0, 'ok': 0, 'msg': '密码错误'}

def userLogin(username, pwd):
    # 字符串一定要在外面套repr(), 巨坑！！！
    username = repr(username)

    conn = POOL.connection()
    cur = conn.cursor()
    response = {'uid': 0, 'ok': 0, 'type': 0, 'last_planid': 0, 'msg': ''}

    sql = ''
    # 查询用户名是否存在
    sql = 'SELECT uid,type,password,last_planid FROM userinfo WHERE username = %s' % (
        username)
    cur.execute(sql)
    data = cur.fetchone()

    if data is None:
        response['msg'] = "用户不存在"
        return response
    print(pwd)
    response['type'] = data[1]
    response['last_planid'] = data[3]
    if data[2] != pwd:
        response['msg'] = "密码错误"
        return response

    uid = data[0]
    cur.close()
    response['uid'] = uid
    response['ok'] = 1

    print(response)
    return response


if __name__ == "__main__":
    # userSignup("lzy", '66666')
    print(userLogin("lzy", '66666'))
